package com.lib76.socket.model;

import java.net.SocketAddress;

import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;

/**
 * Socket通讯通道
 * @author 张浩
 * @version 1.0.0
 */
public class SocketChannel {

	private Channel channel; //通讯通道
	
	public SocketChannel(Channel channel){
		this.channel = channel;
	}
	
	public Integer getId(){
		return channel.getId();
	}
	
	public boolean write(SocketMessage message){
		try{
			if(isAvailable() && channel.isWritable()){
				Object obj = message.output();
				if(obj != null){
					System.out.println("send message : "+obj);
					ChannelFuture future = channel.write(obj);
					if(future != null){
						return true;
					}
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		return false;
	}
	
	public boolean isAvailable(){
		if(channel.isOpen() && channel.isConnected()
				&& (channel.isReadable() || channel.isWritable())){
			return true;
		}
		return false;
	}

	public void close(){
		channel.close();
	}
	
	public SocketAddress getRemoteAddress(){
		return channel.getRemoteAddress();
	}
}
